﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using NLog;
using OddUserManager.Model;
using OddUserManager.Service.IServices;
using OddUserManager.Web.Models;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace OddUserManager.Web.Controllers
{
    public class RealTimeMatchsController : Controller
    {

        static Logger log = LogManager.GetCurrentClassLogger();
        private readonly IRealTimeMatchsService _service;
        private readonly IRealTimeTeamRemarkInfoService _remarkService;
        private readonly IAppUserService _userAppService;

        public RealTimeMatchsController(IRealTimeMatchsService service, IRealTimeTeamRemarkInfoService remarkService,IAppUserService userAppService) {
            _service = service;
            _remarkService = remarkService;
            _userAppService = userAppService;
        }

        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult GetMatchsByTeamParam(RealTimeMatchsParam param) {

            JsonData d = new JsonData();

            try
            {
                List<RealTimeMatchs> list = _service.GetMatchsByParam(param);
                d.Data = list;
            }
            catch (Exception e) {
                d.Success = false;
                d.Message = "查询出错";
                log.Error(e, e.Message);
            }

            return Json(d);
        }

        public IActionResult GetAllMatchsByTeamParam(RealTimeMatchsParam param)
        {

            JsonData d = new JsonData();

            try
            {
                List<RealTimeMatchs> list = _service.GetAllMatchsByParam(param);
                d.Data = list;
            }
            catch (Exception e)
            {
                d.Success = false;
                d.Message = "查询出错";
                log.Error(e, e.Message);
            }

            return Json(d);
        }

        public IActionResult GetLeaguesByParam(RealTimeMatchsParam param) {

            JsonData d = new JsonData();

            try
            {
                List<RealTimeLeagueInfo> list = _service.GetLeagueInfosByParam(param);
                d.Data = list;

            }
            catch (Exception e) {
                d.Success = false;
                d.Message = "查询出错";
                log.Error(e,e.Message);
            }

            return Json(d);

        }


        public IActionResult GetTeamLeagues(RealTimeMatchsParam param) {
            JsonData d = new JsonData();

            try
            {
                List<RealTimeLeagueInfo> list = _service.GetTeamLeagues(param);
                d.Data = list;
            }
            catch (Exception e)
            {
                d.Success = false;
                d.Message = "查询出错";
                log.Error(e, e.Message);
            }

            return Json(d);
        }

        public IActionResult GetTeamSeasons(RealTimeMatchsParam param) {
            JsonData d = new JsonData();

            try
            {
                List<RealTimeSeasonInfo> list = _service.GetTeamSeasons(param);
                d.Data = list;
            }
            catch (Exception e)
            {
                d.Success = false;
                d.Message = "查询出错";
                log.Error(e, e.Message);
            }

            return Json(d);
        }

        public IActionResult GetSeasonsByParam(RealTimeMatchsParam param) {

            JsonData d = new JsonData();
            try
            {
                List<RealTimeSeasonInfo> list = _service.GetSeasonsByParam(param);
                d.Data = list;
            }
            catch (Exception e)
            {
                d.Success = false;
                d.Message = "查询出错";
                log.Error(e, e.Message);
            }

            return Json(d);

        }


        public IActionResult GetMatchTeamInfos(RealTimeMatchsParam param) {
            JsonData d = new JsonData();

            try
            {
                List<RealTimeMatchs> list = _service.GetMatchTeamInfos(param);
                d.Data = list;
            }
            catch (Exception e)
            {
                d.Success = false;
                d.Message = "查询出错";
                log.Error(e, e.Message);
            }

            return Json(d);
        }

        public IActionResult GetNewMatchTeamInfos(RealTimeMatchsParam param)
        {
            JsonData d = new JsonData();

            try
            {
                List<RealTimeMatchs> list = _service.GetMatchTeamInfos(param);
                if (param.HostOrGuest == (int)HostOrGuestType.主场)
                {
                    list = list.OrderBy(p => p.GuestTeamRank).ToList();
                }
                else if (param.HostOrGuest == (int)HostOrGuestType.客场) {
                    list = list.OrderBy(p => p.HostTeamRank).ToList();
                }
                
                d.Data = list;
            }
            catch (Exception e)
            {
                d.Success = false;
                d.Message = "查询出错";
                log.Error(e, e.Message);
            }

            return Json(d);
        }

        public IActionResult GetTeamRankInfo(RealTimeMatchsParam param) {
            JsonData d = new JsonData();

            try
            {
                RealTimeTeamRankInfo model = _service.GetTeamRankInfoByParam(param);
                d.Data = model;
            }
            catch (Exception e)
            {
                d.Success = false;
                d.Message = "查询出错";
                log.Error(e, e.Message);
            }

            return Json(d);
        }

        public async  Task<IActionResult> GetTeamRemarkInfo(int teamId) {
            JsonData d = new JsonData();

            try {
                AppUser user = null;
                var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                if (result.Succeeded)
                {
                    var Id = result.Principal.Identity.Name;
                    user = _userAppService.GetUserById(int.Parse(Id));
                }

                List<TeamRemarkInfo> list = _remarkService.GetTeamRemarkByTeamId(teamId);
                if (list == null || list.Count < 1)
                {
                    list = new List<TeamRemarkInfo>();
                    if (user != null && user.ColorName > 0) {
                        TeamRemarkInfo model = new TeamRemarkInfo();
                        model.TeamId = teamId;
                        model.AppUserId = user.Id;
                        model.AppUserName = user.Name;
                        model.TeamRemark = "";
                        model.IsEdit = 1;
                        model.AppUserIndex = user.ColorName;
                        list.Add(model);
                    }
                }
                else {

                    bool userFlag = false; 
                    for (var i = 0; i < list.Count; i++) {
                        TeamRemarkInfo temp = list[i];
                        if (user != null && user.Id == temp.AppUserId)
                        {
                            userFlag = true;
                            temp.IsEdit = 1;
                        }
                        else {
                            temp.IsEdit = 0;
                        }
                    }

                    // 如果当前分析师不存在数据则添加一条数据
                    if (!userFlag && user.ColorName > 0) {
                        TeamRemarkInfo model = new TeamRemarkInfo();
                        model.TeamId = teamId;
                        model.AppUserId = user.Id;
                        model.AppUserName = user.Name;
                        model.TeamRemark = "";
                        model.IsEdit = 1;
                        model.AppUserIndex = user.ColorName;
                        list.Add(model);
                    }
                }

                d.Data = list;
            }
            catch (Exception e) {

                d.Success = false;
                d.Message = "查询出错";
                log.Error(e,e.Message);
            }

            return Json(d);
        }

        public async Task<IActionResult> EditTeamRemark(TeamRemarkInfo teamRemarkInfo) {
            JsonData d = new JsonData();

            try {

                AppUser user = null;
                var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                if (result.Succeeded)
                {
                    var Id = result.Principal.Identity.Name;
                    user = _userAppService.GetUserById(int.Parse(Id));
                }

                if (user == null || user.ColorName < 1) {
                    d.Success = false;
                    d.Message = "无权限";
                    log.Error("未登陆，无权限");
                    return Json(d);
                }

                if (teamRemarkInfo != null) {
                    TeamRemarkInfo model = _remarkService.GetTeamRemarkByTeamIdAndUserId(teamRemarkInfo.TeamId, user.Id);
                    if (model != null)
                    {
                        model.TeamRemark = teamRemarkInfo.TeamRemark;
                        model.UpdateTime = DateTime.Now;

                    }
                    else {
                        
                        model = teamRemarkInfo;
                        model.Id = 0;
                        model.AppUserId = user.Id;
                        model.AppUserName = user.Name;
                        model.AppUserIndex = user.ColorName;
                        model.CreateTime = DateTime.Now;
                        model.UpdateTime = DateTime.Now;

                    }
                    _remarkService.InsertOrUpdate(model);
                }

                d.Message = "保存成功";
                
            }
            catch (Exception e) {
                d.Success = false;
                d.Message = "保存出错";
                log.Error(e, e.Message);
            }

            return Json(d);
        }


       
    }
}
